package com.example.myshop.service.Imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.myshop.domain.AddressDao;
import com.example.myshop.domain.DistrictDao;
import com.example.myshop.entity.Address;
import com.example.myshop.service.AddressService;
import com.example.myshop.service.DistrictService;
import com.example.myshop.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImp extends ServiceImpl<AddressDao, Address> implements AddressService {
    @Autowired
    private AddressDao addressDao;

    @Autowired
    private DistrictService districtService;


    private Integer maxCount=20;


    @Override
    public void addNewAddress(Long uid, String username, Address address) {
//调用收货地址统计的方法
        QueryWrapper<Address>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        Integer count=addressDao.selectCount(queryWrapper);
        if(count>=maxCount){
            throw new AddressCountLimitException("用户收货地址超出上限");
        }

        //对address对象中的数据进行补全：省市区
        String provinceName= districtService.getNameByCode(address.getProvinceCode());
        String cityName= districtService.getNameByCode(address.getCityCode());
        String areaName= districtService.getNameByCode(address.getAreaCode());
        address.setProvinceName(provinceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);

        //uid、isDelete
        address.setUid(uid);
        Integer isDefault= count==0?1:0;//当count是0说明数据库中无地址数据，将插入的数据设置为默认地址数据1，否则非默认0
        address.setIsDefault(isDefault);

        //补全四项日志
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());

        //插入收货地址的方法
        Integer rows= addressDao.insert(address);
        if(rows!=1){
            throw new InsertException("插入用户的收货地址产生未知异常");
        }
    }

    @Override
    public List<Address> getByUid(Long uid) {
        QueryWrapper<Address>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        List<Address> list=addressDao.selectList(queryWrapper);
        for(Address address:list){
//            address.setUid(null);
            address.setProvinceCode(null);
            address.setCityCode(null);
            address.setAreaCode(null);
            address.setCreatedUser(null);
            address.setCreatedTime(null);
            address.setModifiedUser(null);
            address.setModifiedTime(null);

        }
        return list;
    }

    @Override
    public void setDefault(Long aid, Long uid, String username) {
        QueryWrapper<Address>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("aid",aid);
        Address result= addressDao.selectOne(queryWrapper);
        if(result==null){
            throw new AddressNotFoundException("收货地址不存在");
        }
        //检测当前获取到的收货地址数据归属
//        if(!result.getUid().equals(uid)){
//            throw new AccessDeniedException("非法数据访问");
//        }
        //先将所有收货地址设置为非默认
        UpdateWrapper<Address>updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("is_default",0);
        updateWrapper.eq("uid",uid);
        Integer rows= addressDao.update(null,updateWrapper);
        if(rows<1){
            throw new UpdateException("更新数据时产生未知异常");
        }
        UpdateWrapper<Address>updateWrapper2=new UpdateWrapper<>();
        updateWrapper2.set("is_default",1);
        updateWrapper2.set("modified_time",new Date());
        updateWrapper2.set("modified_user",username);
        updateWrapper2.eq("aid",aid);
        rows=addressDao.update(null,updateWrapper2);
        if(rows!=1){
            throw new UpdateException("更新数据时产生未知异常");
        }
    }

    @Override
    public void delete(Long aid, Long uid, String username) {
        QueryWrapper<Address>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("aid",aid);
        Address result= addressDao.selectOne(queryWrapper);
        if (result == null) {
            // 是：抛出AddressNotFoundException
            throw new AddressNotFoundException("尝试访问的收货地址数据不存在");
        }
        Integer rows1 = addressDao.delete(queryWrapper);
        if (rows1 != 1) {
            throw new DeleteException("删除收货地址数据时出现未知错误");
        }

        // 判断查询结果中的isDefault是否为0
        if (result.getIsDefault() == 0) {
            return;
        }

        // 调用持久层的countByUid()统计目前还有多少收货地址
        QueryWrapper<Address>queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("uid",uid);
        Integer count = addressDao.selectCount(queryWrapper2);
        // 判断目前的收货地址的数量是否为0
        if (count == 0) {
            //直接终止程序
            return;
        }

        // 调用findLastModified()找出用户最近修改的收货地址数据
        queryWrapper2.orderByDesc("modified_time").last("limit 0,1");
        Address lastModified = addressDao.selectOne(queryWrapper2);
        // 从以上查询结果中找出aid属性值
        Long lastModifiedAid = lastModified.getAid();
        // 调用持久层的updateDefaultByAid()方法执行设置默认收货地址，并获取返回的受影响的行数
        UpdateWrapper<Address>updateWrapper2=new UpdateWrapper<>();
        updateWrapper2.set("is_default",1);
        updateWrapper2.set("modified_time",new Date());
        updateWrapper2.set("modified_user",username);
        updateWrapper2.eq("aid",lastModifiedAid);
        Integer rows2 = addressDao.update(null,updateWrapper2);
        // 判断受影响的行数是否不为1
        if (rows2 != 1) {
            // 是：抛出UpdateException
            throw new UpdateException("更新收货地址数据时出现未知错误");
        }
    }

    @Override
    public void updateInfoByAid(Long aid, String username, Address address) {

        QueryWrapper<Address>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("aid",aid);
        Address result= addressDao.selectOne(queryWrapper);
        if(result==null){
            throw new AddressNotFoundException("收货地址不存在");
        }
        address.setAid(aid);
        address.setModifiedUser(username);
        address.setModifiedTime(new Date());
        UpdateWrapper<Address>updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("aid",aid);
        Integer rows=addressDao.update(address,updateWrapper);
        if(rows!=1){
            throw new UpdateException("更新时数据产生位置异常");
        }
    }

    @Override
    public Address getByAid(Long aid, Long uid) {
        QueryWrapper<Address>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("aid",aid);
        Address address= addressDao.selectOne(queryWrapper);
        if(address==null){
            throw new AddressNotFoundException("收货地址数据不存在");
        }
        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedUser(null);
        address.setCreatedTime(null);
        address.setModifiedUser(null);
        address.setModifiedTime(null);

        return address;
    }
}
